<?php

namespace api\zhengmao\controller;


use api\zhengmao\model\OrderModel;
use api\zhengmao\model\UserModel;
use cmf\controller\RestBaseController;
use think\facade\Db;
use think\Request;

class PayController extends RestBaseController
{
    //账户余额支付
    public function walletPay(Request $request)
    {
        $orderId = input('post.order_id');
        $order = OrderModel::find($orderId);
        if (!$order) {
            return json(['status' => 'error', 'message' => '订单不存在']);
        }
        if ($order['status'] != 0) {
            return json(['status' => 'error', 'message' => '该订单已支付']);
        }
        //查询用户
        $user = UserModel::find($request->userID);
        //判断账户余额是否够
        if ($user['wallet'] < $order['total_price']) {
            return json(['status' => 'error', 'message' => '账户余额不足']);
        }
        Db::startTrans();
        try {
            //1.订单的status修改成1
            $order->status = 1;
            $order->pay_type = '账户余额';
            $order->save();

            //2、流水记录
            add_money($order['user_id'], $order['total_price'], '购买商品', 0);

            //3.用户余额修改
            $user->wallet = $user['wallet'] - $order['total_price'];
            $user->save();

            Db::commit();
            return json(['status' => 'success', 'message' => '支付成功']);
        } catch (\Exception $exception) {
            Db::rollback();
            return json(['status' => 'error', 'message' => $exception->getMessage()]);
        }
    }
}